import * as echarts from 'echarts';
import { unref, onMounted, onBeforeUnmount } from 'vue';
import { useEventListener } from '@/hooks/event/useEventListener';
import { isNotEmpty } from '@/utils/is';
export const useEcharts = (elRef, options, defaultColors: any = null) => {
    let chartObj: any = null;
    const chartColors = defaultColors || [
        '#0176D3',
        '#657BA3',
        '#FB7555',
        '#F8BE47',
        '#40AD7E',
        '#1AA5D7',
        '#945FB9',
        '#F279AB',
        '#1E9493',
        '#FF9845'
    ];
    const setOptions = (options) => {
        if (!options.color) {
            options.color = chartColors;
        }
        if (unref(elRef)) {
            if (!chartObj) {
                chartObj = echarts.init(unref(elRef));
            }

            chartObj?.setOption(options);
        }
    };
    const clearChart = () => {
        chartObj?.clear();
    };
    // 自适应窗口大小
    const resize = () => {
        chartObj?.resize();
    };
    onMounted(() => {
        setOptions(unref(options));
    });
    onBeforeUnmount(() => {
        if (isNotEmpty(chartObj)) {
            chartObj.dispose();
            chartObj = null;
        }
    });
    useEventListener({
        fn: resize
    });
    return {
        setOptions,
        clearChart
    };
};
